package com.chalk.util;

import com.chalk.common.constant.CommonConstants;
import com.chalk.common.exception.ServiceException;
import com.chalk.common.util.ResultCode;

import org.springframework.stereotype.Component;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * 抽奖工具类
 *
 * @date: 2019-05-05 下午 06:47
 * @author: zhaobo0119@outlook.com
 * @Descriptopn:
 */
@Component
public class LotteryUtil {

    /**
     * 100%
     */
    private static final int very = 100;

    /**
     * 最大值
     */
    private static final int max = 100;

    /**
     * 最小值
     */
    private static final int min = 1;

    /**
     * 加密key
     */
    private static final String key = "chalk!@#";



    /**
     * 获取2个值之间的随机数
     *
     * @param min 最小值
     * @param max 最大值
     * @return
     */
    private long randomCustom(int min, int max) {
        int range = max - min;
        double rand = Math.random();
        return (min + Math.round(rand * range));
    }

    /**
     * 生成兑奖码
     *
     * @return
     */
    public String createCashCode() {
        UUID uuid = UUID.randomUUID();
        return uuid.toString().split("-")[0].toUpperCase();
    }

    /**
     * DES 加密
     *
     * @param message 要加密的呢容
     * @return
     */
    public static byte[] desEncrypt(String message) {
        try {
            /*Cipher 提供加密和解密的加密密码的功能*/
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");

            /*创建使用前8个字节中一个DESKeySpec对象， key作为DES密钥的密钥材料。*/
            DESKeySpec desKeySpec = new DESKeySpec(key.getBytes(CommonConstants.UTF8));

            /*返回 SecretKeyFactory 对象转换指定算法的密钥*/
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");

            /*根据提供的密钥规范（密钥材料）生成一个 SecretKey对象*/
            SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

            /*化向量IV 创建使用字节来构造一个IvParameterSpec对象 iv作为IV*/
            IvParameterSpec iv = new IvParameterSpec(key.getBytes());

            cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
            return cipher.doFinal(message.getBytes(CommonConstants.UTF8));
        } catch (Exception e) {
            return new byte[0];
        }
    }

    /**
     * DES 解密
     *
     * @param message 要解密的呢容
     * @return
     */
    public static String desDecrypt(byte[] message) {
        try {
            /*Cipher 提供加密和解密的加密密码的功能*/
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");

            /*创建使用前8个字节中一个DESKeySpec对象， key作为DES密钥的密钥材料。*/
            DESKeySpec desKeySpec = new DESKeySpec(key.getBytes(CommonConstants.UTF8));

            /*返回 SecretKeyFactory 对象转换指定算法的密钥*/
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");

            /*根据提供的密钥规范（密钥材料）生成一个 SecretKey对象*/
            SecretKey secretKey = keyFactory.generateSecret(desKeySpec);

            /*化向量IV 创建使用字节来构造一个IvParameterSpec对象 iv作为IV*/
            IvParameterSpec iv = new IvParameterSpec(key.getBytes());

            cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
            return new String(cipher.doFinal(message), CommonConstants.UTF8);
        } catch (Exception e) {
            throw new ServiceException(ResultCode.DECRYPT_FAIL);
        }
    }

    /**
     * Base64 编码
     *
     * @param bytes
     * @return
     */
    public static String Base64Encode(byte[] bytes) {
        BASE64Encoder encoder = new BASE64Encoder();
        String base64_str = encoder.encode(bytes);
        return base64_str;
    }

    /**
     * Base64 解码
     *
     * @param encodedText
     * @return
     */
    public static byte[] Base64DEcode(String encodedText) {
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            return decoder.decodeBuffer(encodedText);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) throws Exception {
        System.out.println(System.currentTimeMillis());
        //byte[] encrypt = desEncrypt("{\"activityId\":\"1126401419576164353\",\"activityItemId\":\"1128588254576570369\",\"itemId\":\"1121341971600801794\",\"prizeId\":\"1129226686266945538\",\"type\":\"0\"}");
        byte[] encrypt = desEncrypt("{\"activityId\":\"\",\"activityItemId\":\"\",\"itemId\":\"\",\"prizeId\":\"1129226686266945538\",\"type\":\"0\"}");
        /*System.out.println(Dncrypt(encrypt));*/
        String s = Base64Encode(encrypt);
        System.out.println("des + base64 encode-------------->" + s);
        /*String dncrypt = desDecrypt(Base64DEcode("ucE6lMOimw4EshX3JuUwO1mUe+lAOnkdfm5XYokPbDfInFezrsvFXT91INJh/00kBLbg+pd7hKq8\n" +
                "KKWw6qG+oKRcI6RH5fFqkpH0dCn7kJEignYZdCBXrhIWZwWdgoiC8Js8g1vNcXCdOKXrNioVZ/o5\n" +
                "zjxwpIzqnG+Ikto16oAfqRFOzy3GVsc/tJNGLF3E79tYo2i6HE59+siR6A73tLFy2JUffdAS"));*/
        String dncrypt = desDecrypt(Base64DEcode(s));
        System.out.println("des decode-------------------->" + dncrypt);
        System.out.println(LotteryUtil.desDecrypt(LotteryUtil.Base64DEcode("xEMSnwsBptOejIwGDm/46O5JQNmzHSEusx4ZAaVUrFG1DdejkM0hPmT+hEViarGsd0JAcVar+hh5ip0UCPLFFw==")));
        System.out.println(LotteryUtil.desDecrypt(LotteryUtil.Base64DEcode("xEMSnwsBptOejIwGDm/46O5JQNmzHSEusx4ZAaVUrFF/z59qyaQUI6vP8vcz+Oc+lYEd6Rn9WLZHoJigOV+8bQ==")));
        System.out.println(LotteryUtil.desDecrypt(LotteryUtil.Base64DEcode("xEMSnwsBptOejIwGDm/46O5JQNmzHSEuhWviUe3UPy33FOXXPI1f6ILVQdwGiw9IWLUqHKCh3H99dGtjCxMstA==")));

    }
}

